package com.we823.cms.repository.service.beetl.tag;

import java.util.ArrayList;
import java.util.List;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.we823.cms.common.web.pageable.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.we823.cms.model.cms.Channel;
import com.we823.cms.repository.service.cms.ChannelService;

@Service("cms_channels")
@Scope("prototype")
public class ChannelListTag extends AbstractListTag {

	private static String PARAM_PARENTID = "parentid";

	@Autowired
	private ChannelService channelService;
	
	@Override
	public void execute() {
		Integer parentid = getParam(PARAM_PARENTID, 0);
		List<Channel> channelModels = null;
		if(parentid==-1){
			if(pageRequest==null){
				channelModels = (sort==null) ? channelService.findAll() : channelService.findAll(sort);
			}else{
				PageInfo<Channel> channelPage = channelService.findAll(pageRequest);
				if(channelPage!=null){
					channelModels = channelPage.getList();
				}
			}
		}else{
			channelModels = getChannelsByParentid(parentid, pageRequest);
			
			if(channelModels!=null){
				for (Channel channelModel : channelModels) {
					List<Channel> childrenChannelModels = getChannelsByParentid(channelModel.getId(), pageRequest);
					channelModel.setChilds(childrenChannelModels);
				}
			}
		}
		
		if(channelModels==null){
			channelModels = new ArrayList<>();
		}
		
		this.binds(channelModels);
	}

	private List<Channel> getChannelsByParentid(Integer parentid, PageRequest pageRequest) {
		List<Channel> channelModels = Lists.newArrayList();
		Channel parent = new Channel();
		parent.setId(parentid);
		if(pageRequest==null){
			channelModels = channelService.findByParent(parent, sort);
		}else{
			PageInfo<Channel> channelPage = channelService.findByParent(parent, pageRequest);
			if(channelPage!=null){
				channelModels = channelPage.getList();
			}
		}
		return channelModels;
	}
}
